package com.ls.markt.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.ls.markt.model.admin.Resources;
import com.ls.markt.service.admin.ResourcesServirce;
import com.ls.markt.util.WebResult;
import com.ls.markt.vo.Response;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

@RestController
@RequestMapping("/resources")
public class ResourcesController {

    @Resource
    ResourcesServirce resourcesServirce;

    @GetMapping("/index")
    public ModelAndView index(){
        return new ModelAndView("admin/resources/index");
    }

    @RequestMapping("/list")
    public JSONObject list(@RequestParam(value="page",required=false,defaultValue="1")int page,
                           @RequestParam(value="rows",required=false,defaultValue="10")int rows){

        PageRequest pageRequest = PageRequest.of(page-1,rows);
        Page<Resources> resources = resourcesServirce.findAll(pageRequest);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",resources.getSize());
        jsonObject.put("rows",resources.getContent());
        return jsonObject;
    }

    @GetMapping("/add")
    public ModelAndView add(){
        return new ModelAndView("admin/resources/add");
    }

    @GetMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable("id")Long id, Model model){
        Resources resources = resourcesServirce.getResourcesById(id);
        model.addAttribute("resources",resources);
        return new ModelAndView("admin/resources/edit","resourcesModel",model);
    }

    @PostMapping("/save")
    public JSONObject save(Resources resources){
        resourcesServirce.saveResources(resources);
        return WebResult.success();
    }

    /**
     * 执行删除资源
     * @param ids
     * @return
     */
    @PostMapping("/doDelete")
    public Response doDelete(@RequestParam Long[] ids){
        resourcesServirce.removeResources(ids);
        return new Response(true);
    }
}
